package com.example.codeanalysis.parser;

import com.example.codeanalysis.parser.AnaResult;
import com.example.codeanalysis.parser.JavaSourceParser;
import com.example.codeanalysis.parser.ResultDTO;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CommandController {

  @GetMapping("/code/parser")
  public ResultDTO parseJava(
      @RequestParam String sysCode,
      @RequestParam String subSysCode,
      @RequestParam String sourceCodePath) {

    ResultDTO dto = new ResultDTO();
    dto.setTotalApiCount(0L);
    dto.setSysCode(sysCode);
    dto.setSubSysCode(subSysCode);

    File sourceCode = new File(sourceCodePath);
    if (sourceCode.isDirectory() && sourceCode.canExecute()) {
      JavaSourceParser parser = new JavaSourceParser(sysCode, subSysCode, sourceCodePath);
      List<AnaResult> resultList = parser.parse();
      dto.setData(resultList);

      dto.setTotalApiCount(resultList.stream()
          .map(AnaResult::getApis)
          .mapToLong(Collection::size)
          .sum());
    } else {
      dto.setData(Collections.emptyList());
    }
    return dto;
  }

}
